package com.hqm.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hqm.dao.ProductDao;
import com.hqm.meta.Product;

@Service
public class ProductServiceImpl implements ProductService {
	@Resource
	private ProductDao productDao;

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean add(Product product) {
		Boolean isAdd = true;
		try {
			productDao.addProduct(product);
		} catch (DataAccessException e) {
			isAdd = false;
			e.printStackTrace();
		}
		
		return isAdd;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean remove(Integer id) {
		Boolean isRemove = true;
		try {
			productDao.deleteProductById(id);
		} catch (DataAccessException e) {
			isRemove = false;
		}
		
		return isRemove;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean update(Product product) {
		Boolean isUpdate = true;
		try {
			productDao.updateProduct(product);
		} catch (DataAccessException e) {
			isUpdate = false;
		}
		
		return isUpdate;
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public Product getProduct(Integer id) {
		Product product = new Product();
		try {
			product = productDao.getProductById(id);
		} catch (DataAccessException e) {
			product = null;
		}
		
		return product;
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public Product getProduct(String title) {
		Product product = new Product();
		try {
			product = productDao.getProductByTitle(title);
		} catch (DataAccessException e) {
			product = null;
		}
		
		return product;
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public Product getProductByImage(String icon) {
		Product product = new Product();
		try {
			product = productDao.getProductByImage(icon);
		} catch (DataAccessException e) {
			product = null;
		}
		
		return product;
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<Product> getProducts() {
		List<Product> products = new ArrayList<Product>();
		try {
			products = productDao.getAllProducts();
		} catch (DataAccessException e) {
			products = null;
		}
		
		return products;
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public Double getProductBuyPrice(Integer id) {
		return productDao.getProductById(id).getPrice();
	}
	
}
